﻿using Microsoft.AspNetCore.SignalR;
using System.Collections.Concurrent;

namespace YunQue.Core.SignalR
{
    public class SignalRHub : Hub
    {
        private static readonly ConcurrentQueue<string> _connectionQueue = new ConcurrentQueue<string>();

        public override Task OnConnectedAsync()
        {
            _connectionQueue.Enqueue(Context.ConnectionId);
            //建立连接的时候，可以在这里处理一些逻辑，比如记录连接信息等
            return base.OnConnectedAsync();
        }

        public override Task OnDisconnectedAsync(Exception? exception)
        {
            _connectionQueue.TryDequeue(out var _);
            return base.OnDisconnectedAsync(exception);
        }

        public new void Dispose()
        {
            base.Dispose();
        }

        public Task SendPublicMsg(string msg)
        {
            return Clients.All.SendAsync("ReceivePublicMsg", msg);
        }

        public Task SendUserMsg(string conId, string msg)
        {
            return Clients.Client(conId).SendAsync("ReceiveUserMsg", msg);
        }

        public Task SendUserMsg(List<string> conIdList, string msg)
        {
            return Clients.Clients(conIdList).SendAsync("ReceiveUserMsg", msg);
        }

        public Task SendAllExceptUserMsg(string exceptConId, string msg)
        {
            return Clients.AllExcept(exceptConId).SendAsync("ReceiveAllExceptUserMsg", msg);
        }


        public Task SendGroupMsg(string groupName, string msg)
        {
            return Clients.Group(groupName).SendAsync("ReceiveGroupMsg", msg);
        }

        public Task SendAllExceptGroupMsg(string groupName,string exceptConId, string msg)
        {
            return Clients.GroupExcept(groupName,exceptConId).SendAsync("ReceiveAllExceptGroupMsg", msg);
        }

        public Task AddToGroup(string groupName,string conId)
        {
            return Groups.AddToGroupAsync(conId, groupName);
        }

        public Task RemoveFromGroup(string groupName,string conId)
        {
            return Groups.RemoveFromGroupAsync(conId, groupName);
        }
    }
}
